var AreaManager = function(){
	var validator = null;
	var gridObj = null;
	var areaTreeObj = null;
	function areaTreeInit(id){
		SysAreaController.getAreaTreeById(null,function(trees){
			ZtreeUtil.initTree("ztree",trees,{
				onClick:function(event, treeId, treeNode){
					if(treeNode.type == "area"){
						viewAreaInfo(treeNode.id);
					}
				},
				beforeClick:function(treeId, treeNode, clickFlag){
					if(treeNode.type == "area"){
						return true;
					}else{
						return false;
					}
				}
				
			},{
				data:{
					key:{
						name: "text",
		    			url: null
					}
				}
			},{

				context:[{
	                id: "addArea",
	                label: "新增地区",
	                visible: function(NODE,TREE_OBJ){
	                	if(NODE.type == "base" ){
	                		return true;
	                	}else{
	                		return false;
	                	}
	                		
	                },
	                action: function(NODE, TREE_OBJ){
	                	citySelectInit();
	                	AppUtils.clearForm("#editAreaForm");
	        			DialogUtils.innerDialog({
	    					    area: ['500px', '450px'],
	    					    title: '新增地区',
	    					    content: $("#editAreaForm"),
	    					    btn: ['保存', '取消'],
	    					    yes: function(index, layero){
	    					    	saveAreaInfo(index);
	    					    },cancel: function(index){
	    					    }
	    				});
	                	
	                }
	            },{
	                id: "editArea",
	                label: "编辑地区",
	                visible: function(NODE,TREE_OBJ){
	                	if(NODE.type=="area"){
	                		return true;
	                	}else{
	                		return false;
	                	}
	                		
	                },
	                action: function(NODE, TREE_OBJ){
	                	editForm(NODE.id);
	                }
	            },{
	                id: "delArea",
	                label: "删除地区",
	                visible: function(NODE,TREE_OBJ){
	                	if(NODE.type=="area"){
	                		return true;
	                	}else{
	                		return false;
	                	}
	                		
	                },
	                action: function(NODE, TREE_OBJ){
	                	Message.confirm('确认删除地区【'+NODE.text+'】吗？', function(index){
	        				SysAreaController.removeAreaById(NODE.id,function(message){
	        					if(message == "success"){
	        						$("#area-info").hide();
	        						Message.success('删除成功');
	        						ZtreeUtil.removeNodeRefreshTree('ztree',NODE);
	        					}else{
	        						Message.error(message);
	        					}
	        					Message.close(index); 
	        				});
	                       
	                    });
	                }
	            }]
			
				
			});
			areaTreeObj = ZtreeUtil.getZtreeObj('ztree');
			if(id !="" && typeof id != 'undefined'){
				//保持选中前状态
				var node = areaTreeObj.getNodeByParam("id",id);
				areaTreeObj.selectNode(node);
			}
		});
	}
	function citySelectInit(){
		$("#province").val("");
		$("#city").val("");
		$("#district").val("");
		$("#city option[value!='']").hide();
		$("#district option[value!='']").hide();
	}
	function viewAreaInfo(areaId,href){
		$("#area-info").show();
		$("#areaId").val(areaId);
		if(href == "inner"){
			$('#areaTab a:first').tab('show');//初始化显示哪个tab
		}else{
			$('#areaTab a:last').tab('show');//初始化显示哪个tab
		}
		
		
		SysAreaController.getAreaById(areaId,function(areaDTO){
			if(areaDTO){
				$.each(areaDTO, function(key, value) {
					var domObj = 'view_' + key;
					if($('#'+domObj).length){
						if(domObj=="view_scrq"){
							value=value.substring(0,19);
						}
						dwr.util.setValue(domObj, value);
					}
				});
			}
		});
		
		if(gridObj== null){
			gridObj = $.fn.bsgrid.init('areaUserTable', {
	            url:contextPath+"/sys/area/user_list.htm",
	            otherParames:{"areaId":areaId},
	            pageSizeSelect: true,
	            stripeRows: true,
	            rowSelectedColor:false,
	            pageSize: 10
				
	        });
		}else{
			gridObj.search({"areaId":areaId});
		}
		
	}
	
	function editForm(areaId){
		dwr.engine.setAsync(false);
		SysAreaController.getAreaById(areaId,function(areaDTO){
			if(areaDTO){
				citySelectInit();
				$("#id").val(areaDTO.id);
				if(areaDTO.description){
					$("#description").val(areaDTO.description);
				}
				$("#city option[value$='_"+areaDTO.provinceId+"']").show();
				$("#district option[value$='_"+areaDTO.cityId+"']").show();
				
				$("#province").val(areaDTO.provinceId);
				$("#city").val(areaDTO.cityId+"_"+areaDTO.provinceId);
				$("#district").val(areaDTO.districtId+"_"+areaDTO.cityId);
				$("#bl").val(areaDTO.bl);
				
					DialogUtils.innerDialog({
					    area: ['500px', '450px'],
					    title: '编辑地区',
					    content: $("#editAreaForm"),
					    btn: ['保存', '取消'],
					    yes: function(index, layero){
					    	saveAreaInfo(index);
					    },cancel: function(index){
					    }
				});
			}else{
				Message.error("部门不存在，请刷新页面");
			}
		});
		dwr.engine.setAsync(true);
		
	}
	
	function saveAreaInfo(index){
		validator.form();
		if (!validator.valid()) {
			return false;
		}
		if($("#district").val()==""){
			Message.error("请选择具体的位置");
			return false;
		}
		var areaDTO = {
				id:$("#id").val(),
				districtId:$("#district").val().split("_")[0],
				description:$("#description").val(),
				bl:$("#bl").val()
				};
		SysAreaController.saveArea(areaDTO,function(newareaDTO){
			if(newareaDTO){
				areaTreeInit(newareaDTO.id);
				if(newareaDTO.id != "" && newareaDTO.id != null){
					if($("#tabs-area-info").is(":visible")){
						viewAreaInfo(newareaDTO.id,"inner");
					}else if($("#area-info").is(":visible")){
						viewAreaInfo(newareaDTO.id);
					}
				}
				Message.success("保存成功！");
			}else{
				Message.error("该地区不存在，请刷新页面！");
			}
			DialogUtils.close(index);
		});
		
	}
	return {
		initAreaTree:function(){
			areaTreeInit();
			validator =$("#areaEditForm").validate({
				rules: {
					description:{maxlength:100}
				}
			});
			$("#province").change(function(){
				var provinceValue=$("#province").val();
				$("#city option[value!='']").hide();
				$("#city option[value$='_"+provinceValue+"']").show();
				$("#city").val("");
				$("#district").val("");
			});
			$("#city").change(function(){
				var cityValue=$("#city").val().split("_")[0];
				$("#district").val("");
				$("#district option[value!='']").hide();
				$("#district option[value$='_"+cityValue+"']").show();
			});
		},
		refreshTree:function(){
			areaTreeInit();
		},
		editAreaByForm:function(areaId){
			editForm(areaId);
		},
		areaFormatter:function(record, rowIndex, colIndex, options){
			return record['userAreaName'];
		},
	    freshUserGrid:function(){
	    	gridObj.refreshPage();
	    },
	    addUserOpen:function(){
			DialogUtils.open({
			    title: '添加人员',
			    area: ['790px', '450px'],
			    fix: false, //不固定
			    maxmin: false,
			    content: contextPath+'/sys/area/adduser.htm?areaId='+$("#areaId").val()
			});
		},
		initAddUserIframe:function(){
			userByNoBmGridObj  = $.fn.bsgrid.init('searchTable', {
	            url:contextPath+"/sys/area/user_noarea_list.htm",
	            pageSizeSelect: true,
	            stripeRows: true,
	            rowSelectedColor:false,
	            pageSize: 10
				
	        });
		},
		addAreaUser:function(record, rowIndex, colIndex, options){
			return '<a href="#" onclick="AreaManager.saveAreaUser(\''+userByNoBmGridObj.getRecordIndexValue(record, 'userId')+'\');">添加</a>';
		},
		saveAreaUser:function(userId){
			SysAreaController.addUserIntoAreaByUserId($("#areaId").val(),userId,function(data){
				if(data){
					Message.success('添加人员成功！');
					userByNoBmGridObj.refreshPage();
					parent.freshGrid();
				}
			});
		},
		
		removeUser:function(){
			var array = AppUtils.gridCheckColumnValue(gridObj,"userId"); 
	    	if(array.length ==0){
	    		Message.error('你还没有选择要删除的用户！');
	    		return false;
	    	}
	    	Message.confirm('您确定要删除该用户？',  function(){
	    		SysAreaController.removeUserAreaInfoByUserArray(array,function(data){
		    		if(data){
		    			Message.success('删除用户成功！');
		    			gridObj.refreshPage();
		    			
		    		}
		    	});
	    	}, function(){
	    	});
		}
	}
}();